// const baseUrl = 'http://39.107.117.43:8080';//测试
// const baseUrl = 'https://cs.hnyoz.com/pts';//测试环境
// const baseUrl = 'https://1883473li5.imdo.co';//本地
const baseUrl = 'https://api-new.hnyoz.com';//生产环境
const mapVxKey = "09bcbbca50e291318c1523bb295254a3";
const httpRequest = (opts, data) => {
	let way = opts.way;
	let httpDefaultOpts = {
		url: baseUrl + '/' + opts.url,
		method: opts.method,
		header: way ? {
			'X-Requested-With': 'XMLHttpRequest',
			"Accept": "application/json",
			"Content-Type": "application/json;charset=UTF-8"
		} : {
			'X-Requested-With': 'XMLHttpRequest',
			'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
		},
		dataType: 'jsonp',
	}
	let promise = new Promise(function(resolve) {
		uni.request(httpDefaultOpts).then(
			(res) => {
				var data = JSON.parse(res[1].data);
				if (data.code == "401") {
					uni.showModal({
						title: '提示',
						content: data.message,
						confirmText: '去登录',
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								uni.redirectTo({
									url: '/pages/login/login'
								});
							}
						}
					});
				} else {
					resolve(data)
				}
			}
		).catch(
			(response) => {
				console.log(response);

			}
		)
	})
	return promise
};
let count = 0;
//带Token请求
const httpTokenRequest = (opts, data) => {
	let token = "";
	if (uni.getStorageSync('token')) {
		token = uni.getStorageSync('token');
	}

	//此token是登录成功后后台返回保存在storage中的
	let way = opts.way;
	let httpDefaultOpts = {
		url: baseUrl + '/' + opts.url,
		data: data,
		method: opts.method,
		header: way ? {
			'Authorization': token,
			'X-Requested-With': 'XMLHttpRequest',
			"Accept": "application/json",
			"Content-Type": "application/json;charset=UTF-8"
		} : {
			'Authorization': token,
			'X-Requested-With': 'XMLHttpRequest',
			'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
		},
		dataType: 'jsonp',
	}
	let promise = new Promise(function(resolve) {
		uni.request(httpDefaultOpts).then(
			(res) => {
				var data = JSON.parse(res[1].data);
				if (data.code == "401") {
					resolve(data)
					if (count == 0) {
						count = 1;
						uni.clearStorageSync('token');
						uni.showModal({
							title: '提示',
							content: data.message,
							confirmText: '去登录',
							showCancel: false,
							success: function(res) {
								if (res.confirm) {
									count = 0;
									uni.redirectTo({
										url: '/pages/login/login'
									});
								}
							}
						});
					}

				} else {
					resolve(data)
				}

			}
		).catch(
			(response) => {
				// resolve(response)
				console.log(response);
			}
		)
	})
	return promise
};

export default {
	baseUrl,
	httpRequest,
	httpTokenRequest,
	mapVxKey
}
